<template>
  <ContentWrap>
    <!-- 搜索工作栏 -->
    <el-form
      class="-mb-15px"
      :model="queryParams"
      ref="queryFormRef"
      :inline="true"
      label-width="68px"
    >
      <el-form-item label="评价计划" prop="planId">
        <el-select
          v-model="queryParams.planId"
          placeholder="请选择评价计划"
          clearable
          filterable
          class="!w-240px"
          @change="handlePlanChange"
        >
          <el-option
            v-for="plan in planList"
            :key="plan.id"
            :label="plan.planName"
            :value="plan.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤日期" prop="attendanceDate">
        <el-date-picker
          v-model="queryParams.attendanceDate"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="!w-240px"
        />
      </el-form-item>
      <el-form-item label="考勤类型" prop="attendanceType">
        <el-select
          v-model="queryParams.attendanceType"
          placeholder="请选择考勤类型"
          clearable
          class="!w-240px"
        >
          <el-option label="理论考试" :value="1" />
          <el-option label="实操考试" :value="2" />
          <el-option label="综合评价" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="考勤状态" prop="attendanceStatus">
        <el-select
          v-model="queryParams.attendanceStatus"
          placeholder="请选择考勤状态"
          clearable
          class="!w-240px"
        >
          <el-option label="出勤" :value="1" />
          <el-option label="缺勤" :value="0" />
          <el-option label="迟到" :value="2" />
          <el-option label="早退" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery"><Icon icon="ep:search" class="mr-5px" /> 搜索</el-button>
        <el-button @click="resetQuery"><Icon icon="ep:refresh" class="mr-5px" /> 重置</el-button>
        <el-button
          type="primary"
          plain
          @click="openForm('create')"
          v-hasPermi="['eval:attendance:create']"
        >
          <Icon icon="ep:plus" class="mr-5px" /> 新增
        </el-button>
        <el-button
          type="info"
          plain
          @click="openBatchCreate"
          v-hasPermi="['eval:attendance:batch-create']"
        >
          <Icon icon="ep:operation" class="mr-5px" /> 批量考勤
        </el-button>
        <el-button
          type="success"
          plain
          @click="handleExport"
          :loading="exportLoading"
          v-hasPermi="['eval:attendance:export']"
        >
          <Icon icon="ep:download" class="mr-5px" /> 导出
        </el-button>
      </el-form-item>
    </el-form>
  </ContentWrap>

  <!-- 考勤统计卡片 -->
  <el-row :gutter="20" class="mb-4" v-if="selectedPlanId">
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-blue-600">{{ attendanceStatistics.totalCandidates || 0 }}</div>
            <div class="text-gray-500">总人数</div>
          </div>
          <Icon icon="ep:user" class="text-4xl text-blue-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-green-600">{{ attendanceStatistics.presentCount || 0 }}</div>
            <div class="text-gray-500">出勤人数</div>
          </div>
          <Icon icon="ep:check" class="text-4xl text-green-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-red-600">{{ attendanceStatistics.absentCount || 0 }}</div>
            <div class="text-gray-500">缺勤人数</div>
          </div>
          <Icon icon="ep:close" class="text-4xl text-red-600" />
        </div>
      </el-card>
    </el-col>
    <el-col :span="6">
      <el-card>
        <div class="flex items-center">
          <div class="flex-1">
            <div class="text-2xl font-bold text-purple-600">{{ attendanceStatistics.attendanceRate || 0 }}%</div>
            <div class="text-gray-500">出勤率</div>
          </div>
          <Icon icon="ep:pie-chart" class="text-4xl text-purple-600" />
        </div>
      </el-card>
    </el-col>
  </el-row>

  <!-- 快速签到区域 -->
  <ContentWrap class="mb-4" v-if="selectedPlanId">
    <div class="flex justify-between items-center mb-4">
      <h3 class="text-lg font-semibold">快速签到</h3>
      <div class="flex gap-2">
        <el-button type="primary" @click="openCheckIn">
          <Icon icon="ep:check" class="mr-1" />
          签到
        </el-button>
        <el-button type="warning" @click="openCheckOut">
          <Icon icon="ep:back" class="mr-1" />
          签退
        </el-button>
      </div>
    </div>
    <div class="text-gray-500">
      当前时间：{{ currentTime }} | 选中计划：{{ selectedPlanName }}
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table v-loading="loading" :data="list" :stripe="true" :show-overflow-tooltip="true">
      <el-table-column label="评价计划" align="center" prop="planName" width="200" />
      <el-table-column label="参评人员" align="center" prop="candidateName" width="120" />
      <el-table-column label="考勤日期" align="center" prop="attendanceDate" width="120" />
      <el-table-column label="考勤类型" align="center" prop="attendanceType" width="120">
        <template #default="scope">
          <dict-tag :type="DICT_TYPE.EVAL_ATTENDANCE_TYPE" :value="scope.row.attendanceType" />
        </template>
      </el-table-column>
      <el-table-column label="签到时间" align="center" prop="checkInTime" width="120">
        <template #default="scope">
          <span v-if="scope.row.checkInTime">{{ scope.row.checkInTime }}</span>
          <span v-else class="text-gray-400">未签到</span>
        </template>
      </el-table-column>
      <el-table-column label="签退时间" align="center" prop="checkOutTime" width="120">
        <template #default="scope">
          <span v-if="scope.row.checkOutTime">{{ scope.row.checkOutTime }}</span>
          <span v-else class="text-gray-400">未签退</span>
        </template>
      </el-table-column>
      <el-table-column label="考勤状态" align="center" prop="attendanceStatus" width="100">
        <template #default="scope">
          <el-tag :type="getAttendanceStatusTagType(scope.row.attendanceStatus)">
            {{ getAttendanceStatusText(scope.row.attendanceStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="考勤说明" align="center" prop="attendanceComments" width="200" />
      <el-table-column
        label="创建时间"
        align="center"
        prop="createTime"
        :formatter="dateFormatter"
        width="180px"
      />
      <el-table-column label="操作" align="center" width="200" fixed="right">
        <template #default="scope">
          <el-button
            link
            type="primary"
            @click="openDetail(scope.row.id)"
            v-hasPermi="['eval:attendance:query']"
          >
            详情
          </el-button>
          <el-button
            link
            type="primary"
            @click="openForm('update', scope.row.id)"
            v-hasPermi="['eval:attendance:update']"
          >
            编辑
          </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button link type="primary">
              更多<Icon icon="ep:arrow-down" class="ml-5px" />
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="checkIn" v-if="!scope.row.checkInTime">
                  补签到
                </el-dropdown-item>
                <el-dropdown-item command="checkOut" v-if="scope.row.checkInTime && !scope.row.checkOutTime">
                  补签退
                </el-dropdown-item>
                <el-dropdown-item command="delete">
                  删除
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      :total="total"
      v-model:page="queryParams.pageNo"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <AttendanceForm ref="formRef" @success="getList" />
  
  <!-- 详情弹窗 -->
  <AttendanceDetail ref="detailRef" />
  
  <!-- 批量考勤弹窗 -->
  <BatchAttendanceForm ref="batchCreateRef" @success="getList" />
  
  <!-- 签到弹窗 -->
  <CheckInForm ref="checkInRef" @success="getList" />
  
  <!-- 签退弹窗 -->
  <CheckOutForm ref="checkOutRef" @success="getList" />
</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import { DICT_TYPE } from '@/utils/dict'
import { 
  EvalAttendanceRecordVO, 
  EvalAttendanceRecordPageReqVO,
  EvalAttendanceStatisticsVO,
  getAttendanceRecordPage, 
  deleteAttendanceRecord, 
  exportAttendanceRecord,
  getAttendanceStatistics,
  checkIn,
  checkOut
} from '@/api/eval/attendance'
import { EvalPlanVO, getPlanListByStatus } from '@/api/eval/plan'
import AttendanceForm from './AttendanceForm.vue'
import AttendanceDetail from './AttendanceDetail.vue'
import BatchAttendanceForm from './BatchAttendanceForm.vue'
import CheckInForm from './CheckInForm.vue'
import CheckOutForm from './CheckOutForm.vue'

/** 考勤管理 列表 */
defineOptions({ name: 'EvalAttendance' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const loading = ref(true) // 列表的加载中
const list = ref<EvalAttendanceRecordVO[]>([]) // 列表的数据
const total = ref(0) // 列表的总页数
const attendanceStatistics = ref<EvalAttendanceStatisticsVO>({} as EvalAttendanceStatisticsVO) // 考勤统计
const planList = ref<EvalPlanVO[]>([]) // 计划列表
const selectedPlanId = ref<number>() // 选中的计划ID
const selectedPlanName = ref<string>() // 选中的计划名称
const currentTime = ref<string>() // 当前时间
const queryParams = reactive<EvalAttendanceRecordPageReqVO>({
  pageNo: 1,
  pageSize: 10,
  planId: undefined,
  attendanceDate: undefined,
  attendanceType: undefined,
  attendanceStatus: undefined
})
const queryFormRef = ref() // 搜索的表单
const exportLoading = ref(false) // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await getAttendanceRecordPage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 计划变更处理 */
const handlePlanChange = async (planId: number) => {
  selectedPlanId.value = planId
  const plan = planList.value.find(p => p.id === planId)
  selectedPlanName.value = plan?.planName || ''
  
  if (planId) {
    // 加载考勤统计
    await loadAttendanceStatistics(planId)
  }
}

/** 加载考勤统计 */
const loadAttendanceStatistics = async (planId: number) => {
  try {
    attendanceStatistics.value = await getAttendanceStatistics(planId)
  } catch (error) {
    console.error('加载考勤统计失败:', error)
  }
}

/** 更新当前时间 */
const updateCurrentTime = () => {
  const now = new Date()
  currentTime.value = now.toLocaleString()
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  selectedPlanId.value = undefined
  selectedPlanName.value = undefined
  handleQuery()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 详情操作 */
const detailRef = ref()
const openDetail = (id: number) => {
  detailRef.value.open(id)
}

/** 批量考勤操作 */
const batchCreateRef = ref()
const openBatchCreate = () => {
  if (!selectedPlanId.value) {
    message.warning('请先选择评价计划')
    return
  }
  batchCreateRef.value.open(selectedPlanId.value)
}

/** 签到操作 */
const checkInRef = ref()
const openCheckIn = () => {
  if (!selectedPlanId.value) {
    message.warning('请先选择评价计划')
    return
  }
  checkInRef.value.open(selectedPlanId.value)
}

/** 签退操作 */
const checkOutRef = ref()
const openCheckOut = () => {
  if (!selectedPlanId.value) {
    message.warning('请先选择评价计划')
    return
  }
  checkOutRef.value.open(selectedPlanId.value)
}

/** 更多操作 */
const handleCommand = async (command: string, row: EvalAttendanceRecordVO) => {
  switch (command) {
    case 'checkIn':
      await handleCheckIn(row.planId, row.candidateInfoId)
      break
    case 'checkOut':
      await handleCheckOut(row.planId, row.candidateInfoId)
      break
    case 'delete':
      await handleDelete(row.id!)
      break
  }
}

/** 补签到 */
const handleCheckIn = async (planId: number, candidateInfoId: number) => {
  try {
    await checkIn(planId, candidateInfoId)
    message.success('签到成功')
    await getList()
    if (selectedPlanId.value) {
      await loadAttendanceStatistics(selectedPlanId.value)
    }
  } catch {}
}

/** 补签退 */
const handleCheckOut = async (planId: number, candidateInfoId: number) => {
  try {
    await checkOut(planId, candidateInfoId)
    message.success('签退成功')
    await getList()
    if (selectedPlanId.value) {
      await loadAttendanceStatistics(selectedPlanId.value)
    }
  } catch {}
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await deleteAttendanceRecord(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await exportAttendanceRecord(queryParams)
    download.excel(data, '考勤记录.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}

/** 获取考勤状态标签类型 */
const getAttendanceStatusTagType = (status: number) => {
  const typeMap = { 0: 'danger', 1: 'success', 2: 'warning', 3: 'warning' }
  return typeMap[status] || ''
}

/** 获取考勤状态文本 */
const getAttendanceStatusText = (status: number) => {
  const textMap = { 0: '缺勤', 1: '出勤', 2: '迟到', 3: '早退' }
  return textMap[status] || '未知'
}

/** 加载计划列表 */
const loadPlanList = async () => {
  try {
    // 获取进行中的计划
    planList.value = await getPlanListByStatus(4) // 进行中
  } catch (error) {
    console.error('加载计划列表失败:', error)
  }
}

/** 初始化 **/
onMounted(() => {
  loadPlanList()
  getList()
  updateCurrentTime()
  
  // 每分钟更新一次时间
  setInterval(updateCurrentTime, 60000)
})
</script>
